
const Util = require('Util');


cc.Class({
    extends: cc.Component,

    properties: {
        showCount: 2,

        cardPrefab: cc.Prefab
    },

    onLoad() {
        this.cards = [];

        let range = [4, 32];
        this.logRange = [Math.log2(range[0]), Math.log2(range[1])];

        this.dealCards();
    },

    generateCard() {
        let cardNum = 2 ** Util.random(this.logRange[0], this.logRange[1]);

        let cardNode = cc.instantiate(this.cardPrefab);
        cardNode.parent = this.node;

        let card = cardNode.getComponent('Card');
        card.setNum(cardNum);

        return card;
    },
    dealCards() {
        let cardStartX = 0;
        for (let i = 0; i < this.showCount; i++) {
            let card = this.generateCard();
            this.cards.push(card);
            card.zIndex = -i;

            cardStartX += -i * (card.width / 2);
            card.x = cardStartX;
        }
    },

    getTopCard() {
        return this.cards[0];
    },
    shiftCard() {
        let card = this.cards.shift();
        card.node.removeFromParent();

        let newCard = this.generateCard();
        this.cards.push(newCard);

        let lastIdx = this.cards.length - 1;
        newCard.zIndex = -lastIdx;
        newCard.x = this.cards[lastIdx - 1].x;

        let curCard = this.getTopCard();
        curCard.zIndex = 0;
        curCard.x = 0;

        this.node.emit('change-top');

        return card;
    }
});
